package cn.com.xinjinfu.pdoulcProduct.activity.recharge;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.MyVoucherBean;
import cn.com.xinjinfu.pdoulcProduct.entity.MyVoucherBean.VoucherListA;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.utils.LoginRequestUtils;
import cn.com.xinjinfu.pdoulcProduct.xlistview.XListView;

/**
 * 选择兜券
 * Created by android-adt on 2016/6/7.
 */
public class SelectVoucherList extends BaseActivity implements XListView.IXListViewListener, View.OnClickListener{
    private  LinearLayout no_invest_view;
    private XListView xListView;
    private RequestQueue requen;
    private MyAdapet mAdapter;
    private MyVoucherBean myVoucher;
    private List<VoucherListA> page;
    private int itemId,itemAmount,type;
    private double rate;
    private int unableitemId = -1;
    private String buyAmount,bidType;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_voucher_list);
        TitleManager.showTitle(SelectVoucherList.this, "选择兜券", "");
        Intent intent = getIntent();
        bidType = intent.getStringExtra("bidType");
        buyAmount = intent.getStringExtra("buyAmount");
        itemId = intent.getIntExtra("itemId",0);
        itemAmount = intent.getIntExtra("itemAmount",0);
        type = intent.getIntExtra("type",0);
        rate = intent.getIntExtra("rate",0);
        unableitemId = intent.getIntExtra("itemId",-1);
        initViews();
        requen = Volley.newRequestQueue(this);
        loginRequest();
    }

    private void initViews() {
        no_invest_view = (LinearLayout) findViewById(R.id.no_invest_view);
        xListView = (XListView) findViewById(R.id.xListView);
        xListView.setPullLoadEnable(false);// 是否显示下拉刷新和上啦加载
        xListView.setPullRefreshEnable(false);
        xListView.setXListViewListener(this);
        //单选设置
        xListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
//        xListView = (ListView) findViewById(R.id.xListView);
        mAdapter = new MyAdapet(this);
        xListView.setAdapter(mAdapter);
        if (unableitemId != -1){
            mAdapter.setUnable(true,unableitemId);
        }
        xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                L.d("position==========" + position);
                if (position > 0) {
                    if (page.get(position - 1).getUsable() == 1) {
                        itemId = page.get(position - 1).getId();
                        itemAmount = page.get(position - 1).getAmount();
                        type = page.get(position - 1).getType();
                        rate = page.get(position - 1).getRate();
                        if (unableitemId != -1 && unableitemId == itemId) {
                            unableitemId = -1;
                            mAdapter.setUnable(false, itemId);
                            itemAmount=0;itemId=0;type=0;rate=0;
                        } else {
                            mAdapter.setUnable(true, itemId);
                            returnUp();
                        }
                    }
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        returnUp();
    }

    public void returnUp(){
        Intent intent = new Intent();
        intent.putExtra("itemId", itemId);
        intent.putExtra("itemAmount", itemAmount);
        intent.putExtra("type", type);
        intent.putExtra("rate", rate);
        setResult(RESULT_OK, intent);
        finish();
    }


    /**
     * 网络请求
     */
    private void loginRequest() {
        User user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1427");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("bidType", bidType);
            parameters.put("buyAmount", buyAmount);
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, null);
            requen.add(request);
        }
    }

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("代金券列表 ==========" + jobj);
            myVoucher = JSON.parseObject(jobj.toString(), MyVoucherBean.class);
            page = myVoucher.getVoucherListA();
            if (page == null || page.isEmpty()){
                no_invest_view.setVisibility(View.VISIBLE);
            }else {
                no_invest_view.setVisibility(View.GONE);
                mAdapter.addList(page);
                xListView.setItemChecked(2, false);

            }
        }
    };

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {

    }

    @Override
    public void onClick(View v) {

    }


    private class MyAdapet extends BaseAdapter {

        private Activity context;
        private LayoutInflater inflater;
        private List<VoucherListA> list;
        private VoucherListA termList;
        private boolean unable;
        private int id;

        public void setUnable(boolean unable,int id) {
            this.unable = unable;
            this.id = id;
            notifyDataSetChanged();
        }

        public void setList(List<VoucherListA> page) {
            list.clear();
            list.addAll(page);
            notifyDataSetChanged();
        }
        public void addList(List<VoucherListA> page) {
            list.addAll(page);
            notifyDataSetChanged();
        }

        public MyAdapet(Activity context) {
            inflater = LayoutInflater.from(context);
            this.context = context;
            list = new ArrayList<>();
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list == null ? 0 : list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            //普通列表项
            if (convertView == null || convertView.getTag() == null) {
                convertView = inflater.inflate(R.layout.item_voucher_list, null);
                holder = new ViewHolder();
                holder.bg_item = (LinearLayout) convertView.findViewById(R.id.bg_item);
                holder.btn_ok2 = (ImageView) convertView.findViewById(R.id.btn_ok2);
                holder.tv_money = (TextView) convertView.findViewById(R.id.tv_money);
                holder.tv_yuan = (TextView) convertView.findViewById(R.id.tv_yuan);
                holder.quan_type = (TextView) convertView.findViewById(R.id.quan_type);
                holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);
                holder.tv_infor = (TextView) convertView.findViewById(R.id.tv_infor);
                holder.tv_need_money = (TextView) convertView.findViewById(R.id.tv_need_money);
                holder.tv_app_pc = (TextView) convertView.findViewById(R.id.tv_app_pc);
                holder.textView1 = (LinearLayout) convertView.findViewById(R.id.textView1);
                convertView.setTag(holder);//绑定ViewHolder对象
            } else {
                holder = (ViewHolder) convertView.getTag();//取出ViewHolder对象
            }
            termList = list.get(position);
            L.d("-------"+termList.toString());
            holder.quan_type.setText(termList.getTitle());
            if (termList.getType() == 1) {
                holder.tv_money.setText("" + termList.getRate());
                holder.tv_yuan.setText("%");
            } else {
                holder.tv_money.setText("" + termList.getAmount());
                holder.tv_yuan.setText("元");
            }
            if (termList.getInvest_type() == 1) {
                holder.tv_infor.setText("定期标的可用");
            } else if (termList.getInvest_type() == 2) {
                holder.tv_infor.setText("转让标的可用");
            } else {
                holder.tv_infor.setText("定期、转让标的可用");
            }
            if (termList.getPlatform_type() == 1) {
                holder.tv_app_pc.setText("APP");
            } else if (termList.getPlatform_type() == 2) {
                holder.tv_app_pc.setText("PC");
            } else {
                holder.tv_app_pc.setText("APP/PC");
            }
            GradientDrawable myGrad = (GradientDrawable) holder.bg_item.getBackground();
            if (termList.getUsable() == 1) {
                holder.tv_time.setText(termList.getReceice_time() + "-" + termList.getExpire_time());
                myGrad.setColor(0xFF6ED3D6);
            } else {
                holder.tv_time.setText(termList.getReceice_time() + "-" + termList.getExpire_time());
                myGrad.setColor(0xFFCCCCCC);
            }
            if (termList.getLimit_amount() > 0){
                holder.textView1.setVisibility(View.VISIBLE);
                holder.tv_need_money.setText("" + termList.getLimit_amount());
            }else {
                holder.textView1.setVisibility(View.INVISIBLE);
            }

            if (unable && id == termList.getId()){
                holder.btn_ok2.setVisibility(View.VISIBLE);
            }else {
                holder.btn_ok2.setVisibility(View.GONE);
            }

            return convertView;
        }

        public final class ViewHolder {
            public LinearLayout bg_item;
            public ImageView btn_ok2;
            public TextView tv_money;
            public TextView tv_yuan;
            public TextView quan_type;
            public TextView tv_time;
            public TextView tv_infor;
            public TextView tv_need_money;
            public TextView tv_app_pc;
            public LinearLayout textView1;
        }
    }
}
